package com.kkshop.test.fixture;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;

public class NewProductFixture implements Fixture {
    
    private static final String INSERT_PRODUCT_SQL = "INSERT INTO products VALUES(?, ?, ?)";
    private static final String DELETE_PRODUCT_SQL = "DELETE FROM products WHERE id = ?";
    
    private DataSource dataSource;
    private Long id;
    private Long categoryId;
    private String name;
    
    public NewProductFixture(DataSource dataSource, Long id, Long categoryId, String name) {
        this.dataSource = dataSource;
        this.id = id;
        this.categoryId = categoryId;
        this.name = name;
    }

    public void setUp() throws Exception {
        JdbcTemplate template = new JdbcTemplate(dataSource);
        template.execute(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement statement = connection.prepareStatement(INSERT_PRODUCT_SQL);
                statement.setLong(1, id);
                statement.setLong(2, categoryId);
                statement.setString(3, name);
                return statement;
            }
        }, new PreparedStatementCallback() {
            public Object doInPreparedStatement(PreparedStatement statement) throws SQLException, DataAccessException {
                statement.execute();
                return null;
            }
        });
    }

    public void tearDown() throws Exception {
        JdbcTemplate template = new JdbcTemplate(dataSource);
        template.execute(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement statement = connection.prepareStatement(DELETE_PRODUCT_SQL);
                statement.setLong(1, id);
                return statement;
            }
        }, new PreparedStatementCallback() {
            public Object doInPreparedStatement(PreparedStatement statement) throws SQLException, DataAccessException {
                statement.execute();
                return null;
            }
        });
    }

}
